package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.IdUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IAgencyCertificationAuditService;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * <p>
 * 机构认证审核表 服务实现类
 * </p>
 *
 * @author szc
 * @since 2025-09-17
 */
@Service
public class AgencyCertificationAuditServiceImpl extends ServiceImpl<AgencyCertificationAuditMapper, AgencyCertificationAudit> implements IAgencyCertificationAuditService {

    @Resource
    private IAgencyCertificationService agencyCertificationService;

    /**
     * 机构认证
     * @param agencyCertificationAuditAddReqDTO 机构认证审核表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void certification(AgencyCertificationAuditAddReqDTO agencyCertificationAuditAddReqDTO) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        AgencyCertification agencyCertification = BeanUtil.toBean(agencyCertificationAuditAddReqDTO, AgencyCertification.class);
        agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        agencyCertification.setId(currentUser.getId());
        agencyCertification.setCertificationTime(LocalDateTime.now());

        // 判断是否已提交过认证信息
        LambdaQueryWrapper<AgencyCertification> queryWrapper = Wrappers.<AgencyCertification>lambdaQuery()
                .eq(AgencyCertification::getId, currentUser.getId());
        AgencyCertification agencyCertificationServiceDb = agencyCertificationService.getOne(queryWrapper);
        if (ObjectUtils.isNull(agencyCertificationServiceDb)) {
            //插入机构认证信息表
            agencyCertificationService.save(agencyCertification);
        } else if (agencyCertificationServiceDb.getCertificationStatus().equals(CertificationStatusEnum.FAIL.getStatus())){
            //更新机构认证信息表
            agencyCertification.setUpdateTime(LocalDateTime.now());
            agencyCertification.setId(agencyCertificationServiceDb.getId());
            agencyCertificationService.updateById(agencyCertification);
        }

        //插入机构认证审核表
        AgencyCertificationAudit bean = BeanUtil.toBean(agencyCertificationAuditAddReqDTO, AgencyCertificationAudit.class);
        bean.setId(IdUtils.getSnowflakeNextId());
        bean.setServeProviderId(currentUser.getId());
        save(bean);
    }


    /**
     * 查询最新驳回原因
     *
     * @return 驳回原因
     */
    @Override
    public RejectReasonResDTO getRejectReason() {
        CurrentUser currentUser = UserContext.getCurrentUser();
        String result = Optional.ofNullable(lambdaQuery()
                        .eq(AgencyCertificationAudit::getServeProviderId, currentUser.getId())
                        .eq(AgencyCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                        .eq(AgencyCertificationAudit::getAuditStatus, 1)
                        .orderByDesc(AgencyCertificationAudit::getCreateTime)
                        .last("limit 1")
                        .select(AgencyCertificationAudit::getRejectReason)
                        .one())
                .map(AgencyCertificationAudit::getRejectReason)
                .orElse("");
        return new RejectReasonResDTO(result);
    }

    /**
     * 分页查询
     *
     * @param agencyCertificationAuditPageQueryReqDTO 查询参数
     * @return 分页结果
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> pageQuery(AgencyCertificationAuditPageQueryReqDTO agencyCertificationAuditPageQueryReqDTO) {
        return PageHelperUtils.selectPage(agencyCertificationAuditPageQueryReqDTO, () ->
                baseMapper.queryList(agencyCertificationAuditPageQueryReqDTO.getName(),
                        agencyCertificationAuditPageQueryReqDTO.getLegalPersonName(),
                        agencyCertificationAuditPageQueryReqDTO.getAuditStatus(),
                        agencyCertificationAuditPageQueryReqDTO.getCertificationStatus()));
    }

    /**
     * 审核机构认证信息
     *
     * @param certificationStatus 认证状态
     * @param rejectReason        驳回原因
     * @param id                  审核项ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(Integer certificationStatus, String rejectReason, Long id) {
        AgencyCertificationAudit agencyCertificationAudit = getById(id);
        if (agencyCertificationAudit == null) {
            throw new ForbiddenOperationException("认证信息不存在");
        }
        Long serveProviderId = agencyCertificationAudit.getServeProviderId();
        // 更新机构认证信息表
        agencyCertificationService.lambdaUpdate()
                .eq(AgencyCertification::getId, serveProviderId)
                .set(AgencyCertification::getCertificationStatus, certificationStatus)
                .set(AgencyCertification::getUpdateTime, LocalDateTime.now())
                .update();
        // 更新机构认证审核表
        lambdaUpdate().eq(AgencyCertificationAudit::getId, id)
                .set(AgencyCertificationAudit::getAuditStatus, 1)
                .set(AgencyCertificationAudit::getAuditTime, LocalDateTime.now())
                .set(AgencyCertificationAudit::getCertificationStatus, certificationStatus)
                .set(StringUtils.isNotBlank(rejectReason), AgencyCertificationAudit::getRejectReason, rejectReason)
                .set(AgencyCertificationAudit::getAuditorId, UserContext.getCurrentUser().getId())
                .set(AgencyCertificationAudit::getAuditorName, UserContext.getCurrentUser().getName())
                .set(AgencyCertificationAudit::getUpdateTime, LocalDateTime.now())
                .update();
    }
}
